using System;
using System.IO;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Interop;
using ScreenRecorderLib;

namespace WpfWindowRecorder
{
    public class MainWindowRecorder
    {
        private Recorder? _recorder;
        private string? _outputFilePath;
        private TaskCompletionSource<string?>? _recordingTcs;

        public async Task StartRecordingAsync(Window mainWindow)
        {
            var hwnd = new WindowInteropHelper(mainWindow).Handle;

            var desktopPath = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory);
            _outputFilePath = Path.Combine(desktopPath, $"MainWindowCapture_{DateTime.Now:yyyyMMdd_HHmmss}.mp4");

            var options = new RecorderOptions
            {
                AudioOptions = new AudioOptions
                {
                    IsAudioEnabled = false
                },
                OutputOptions = new OutputOptions
                {
                    RecorderMode = RecorderMode.Video,
                    Stretch = StretchMode.Uniform,
                    OutputFrameSize = new ScreenSize(1920, 1080)
                },
                SourceOptions = new SourceOptions
                {
                    RecordingSources = new List<RecordingSourceBase>
                          {
                              new WindowRecordingSource(hwnd) // Use WindowRecordingSource to specify the window handle  
                          }
                }
            };

            _recorder = Recorder.CreateRecorder(options);

            _recordingTcs = new TaskCompletionSource<string?>();

            _recorder.OnRecordingComplete += (s, e) =>
            {
                _recordingTcs?.TrySetResult(_outputFilePath);
            };
            _recorder.OnRecordingFailed += (s, e) =>
            {
                _recordingTcs?.TrySetException(new Exception(e.Error));
            };
            _recorder.OnStatusChanged += (s, e) => { /* Optionally handle status changes */ };

            // Start recording  
            _recorder.Record(_outputFilePath);
        }

        public async Task<string?> StopAndSaveRecordingAsync()
        {
            if (_recorder == null)
                return null;

            _recorder.Stop();
            if (_recordingTcs != null)
            {
                try
                {
                    // Wait for the recording to complete and file to be saved    
                    var result = await _recordingTcs.Task;
                    return result;
                }
                finally
                {
                    _recorder.Dispose();
                    _recorder = null;
                    _recordingTcs = null;
                }
            }
            return _outputFilePath;
        }
    }

}
